package br.com.lumis.ims.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import br.com.lumis.ims.model.Disco;
import br.com.lumis.ims.model.Instancia;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceBlockDeviceMapping;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.Tag;

public class EC2Service {
	
	public List<Instancia> getServidores(AWSCredentials credentials) {
		AmazonEC2 ec2 = new AmazonEC2Client(credentials);
		
		DescribeInstancesResult resultado = ec2.describeInstances();
		
		List<Instancia> retorno = new ArrayList<Instancia>();
		
		Iterator<Reservation> itReservations = resultado.getReservations().iterator();
		while(itReservations.hasNext()) {
			Reservation reservation = itReservations.next();
			Iterator<Instance> itInstance = reservation.getInstances().iterator();
			while(itInstance.hasNext()) {
				Instance instance = itInstance.next();
				Instancia obj = new Instancia();
				
				obj.setId(instance.getInstanceId());
				
				Iterator<Tag> itTags = instance.getTags().iterator();
				while(itTags.hasNext()) {
					Tag tag = itTags.next();
					if(tag.getKey().equals("Name")) {
						obj.setNome(tag.getValue());
					} else if(tag.getKey().equals("Description")) {
						obj.setDescricao(tag.getValue());
					}
				}
				
				List<Disco> discos = new ArrayList<Disco>();
				Iterator<InstanceBlockDeviceMapping> itBlocks = instance.getBlockDeviceMappings().iterator();
				while(itBlocks.hasNext()) {
					InstanceBlockDeviceMapping block = itBlocks.next();
					Disco disco = new Disco();
					
					disco.setId(block.getEbs().getVolumeId());
					disco.setDevice(block.getDeviceName());
					
					discos.add(disco);
				}
				obj.setDiscos(discos);
				
				retorno.add(obj);
			}
		}
		
		return retorno;
	}

}
